<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      class="filter-search"
      :model="queryParams"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话" prop="tel">
        <el-input
          v-model="queryParams.tel"
          placeholder="请输入电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择用户状态" clearable @change="handleQuery">
          <el-option
            v-for="dict in $dict.normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="float: right;">
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="content-box">
      <el-row :gutter="10" class="mb20">
        <el-col :span="1.5">
          <el-button
            v-has-perm="['permission:role:add']"
            type="primary"
            plain
            :icon="Plus"
            @click="openSelectUser"
          >添加用户
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-has-perm="['permission:role:delete']"
            type="danger"
            plain
            :icon="CircleClose"
            :disabled="multiple"
            @click="cancelAuthUserAll"
          >批量取消授权
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            :icon="Close"
            @click="handleClose"
          >关闭
          </el-button>
        </el-col>
        <div style="flex: 1" />
        <right-toolbar v-model:show-search="showSearch" @query-table="getList" />
      </el-row>

      <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户名称" prop="userName" :show-overflow-tooltip="true" />
        <el-table-column label="邮箱" prop="email" :show-overflow-tooltip="true" />
        <el-table-column label="手机" prop="tel" :show-overflow-tooltip="true" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="$dict.normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-has-perm="['permission:role:delete']"
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              :icon="CircleClose"
              @click="cancelAuthUser(scope.row)"
            >取消授权
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageIndex"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <select-user ref="selectRef" :role-id="queryParams.roleId" @ok="handleQuery" />
  </div>
</template>

<script setup>
import { CircleClose, Close, Plus, Refresh, Search } from '@element-plus/icons-vue'
import selectUser from './selectUser.vue'
import { parseTime } from "@/utils/index.js"
import tab from "@/plugins/tab.js"

const route = useRoute()
const selectRef = ref(null)


// 响应式状态
const loading = ref(true)
const userIds = ref([])
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const userList = ref([])

const queryParams = reactive({
  pageIndex: 1,
  pageSize: 10,
  roleId: route.params?.roleId,
  userName: undefined,
  tel: undefined,
  status: undefined
})
const getList = () => {
  loading.value = true
  $xl.apis.allocatedUserList({params: queryParams}).then(res => {
    userList.value = res.data.records
    total.value = res.data.total
    loading.value = false
  }).catch(err => {
    $xl.modal.msgError(err)
    loading.value = false
  })
}

const handleClose = () => {
  const obj = {path: '/permission/role'}
  tab.closeOpenPage(obj)
}

const handleQuery = () => {
  queryParams.pageIndex = 1
  getList()
}

const proxy = getCurrentInstance()

function resetQuery() {
  proxy.refs.queryForm.resetFields()
  handleQuery()
}

const handleSelectionChange = (selection) => {
  userIds.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

const openSelectUser = () => {
  selectRef.value.show()
}

const cancelAuthUser = (row) => {
  const roleId = queryParams.roleId
  $xl.modal.confirm(`确认要取消该用户"${ row.userName }"角色吗？`).then(() => {
    return $xl.apis.cancelAuthUser({
      params: {
        userId: row.id,
        roleId: roleId
      }
    }).then(() => {
      getList()
      $xl.modal.msgSuccess('取消授权成功')
    })
  }).catch(() => {
  })
}

const cancelAuthUserAll = () => {
  const roleId = queryParams.roleId
  $xl.modal.confirm('是否取消选中用户授权数据项？').then(() => {
    return $xl.apis.multipleCancelAuthUser({
      params: {
        userIds: userIds.value,
        roleId: roleId
      }
    }).then(() => {
      getList()
      $xl.modal.msgSuccess('取消授权成功')
    })
  }).catch(() => {
  })
}

// 生命周期钩子
onMounted(() => {
  const roleId = route.params?.roleId
  if (roleId) {
    queryParams.roleId = roleId
    getList()
  }
})

// 暴露给模板的属性和方法
defineExpose({
  getList
})
</script>
